package org.space.galaxyCabinet.handler.impl;

import com.alibaba.fastjson2.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.space.galaxyCabinet.annotation.GuiguEmqx;
import org.space.galaxyCabinet.clients.DeviceStatusClients;
import org.space.galaxyCabinet.constant.EmqxConstants;
import org.space.galaxyCabinet.domain.DeviceStatus;
import org.space.galaxyCabinet.handler.MassageHandler;
import org.space.galaxyCabinet.service.InfluxDBService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.Instant;

@Slf4j
@Component
@GuiguEmqx(topic = EmqxConstants.DEVICE_ALL_STATUS)
public class DeviceStatusHandler implements MassageHandler {

    @Autowired
    private DeviceStatusClients deviceStatusClients;

    @Autowired
    private InfluxDBService influxDBService;

    @Override
    public void handleMessage(JSONObject message) {
        log.info("开始处理设备属性上报消息...");
        try {
            // 检查消息是否为空
            if (message == null || message.isEmpty()) {
                log.warn("收到空消息");
                return;
            }
            DeviceStatus deviceStatus = new DeviceStatus();
            deviceStatus.setDeviceNo(message.getString("deviceNo"));
            deviceStatus.setHumidity(message.getFloat("humidity"));
            deviceStatus.setTemperature(message.getFloat("temperature"));
//            deviceStatus.setStatus(message.getInteger("status"));
            deviceStatus.setTimestamp(Instant.now());
            log.info("deviceStatus: {}", JSONObject.toJSONString(deviceStatus));
            log.info("上传到influxDB:{}", influxDBService.uploadedDeviceStatus(deviceStatus));
            log.info("上传设备数据信息：{}", deviceStatusClients.updateByDeviceNo(deviceStatus));     // 上传设备数据信息
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
